package com.wildlife.springboot.mapper.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
public class SoundUploadService {

    private static final String UPLOAD_DIR = "D:/Program Files (x86)/IdeaProjects/Wildlife/sounds";

    public List<Map<String, String>> uploadSounds(List<MultipartFile> files) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        List<Map<String, String>> uploadedFiles = new ArrayList<>();

        for (MultipartFile file : files) {
            // 获取文件名并生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

            // 限制文件格式
            if (!fileExtension.equals(".txt") && !fileExtension.equals(".fasta")) {
                throw new IOException("不支持的文件类型: " + fileExtension);
            }

            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath);

            // 存储原始文件名和路径
            Map<String, String> fileInfo = new HashMap<>();
            fileInfo.put("path", "sounds/" + uniqueFilename);
            fileInfo.put("originalFilename", originalFilename);
            uploadedFiles.add(fileInfo);
        }

        return uploadedFiles;
    }

    public String readFileContent(String filePath) throws IOException {
        Path path = Paths.get(UPLOAD_DIR, filePath.replace("sounds/", ""));
        return Files.readString(path);
    }
}
